package com.springfairytale.qqserver.main;

import java.io.IOException;
import java.net.Socket;

import com.springfairytale.qq.common.Protocol;
import com.springfairytale.qqserver.action.BaseAction;
import com.springfairytale.qqserver.action.Invoker;

public class ClientRunnable implements Runnable {
	private Socket socket;
	private Protocol protocol;
	private boolean flag = true;
	private Invoker invoker;

	public ClientRunnable(Socket socket) {
		this.socket = socket;
		invoker = new Invoker();

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (flag) {
			try {
				go();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				// Context.sockets.remove(userid);

				try {
					socket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				flag = false;
			}
		}
	}

	private void go() throws IOException {
		protocol = Protocol.getProtocol(socket);
		int action = protocol.getAction();

		BaseAction act = Context.actions.get(action);
		act.setReceiver(protocol, socket);
		invoker.setAction(act);
		invoker.process();

	}

}
